<?php

class Stock_Model extends Model {

    public function __construct() {
        parent::__construct();
        //echo "stock_model";
    }

    public function getData() {
        $data = array('msg'=>'', 'list'=>null);
        if(isset($_GET['stockId']) && !empty($_GET['stockId'])){
            $data['stockId'] = intval($_GET['stockId']);

            $data['view'] = 'detail';
            //$data['stockId'] = intval($_GET['stockId']);

            //var_dump($einkauflist);

            $this->updateStock($data['stockId']);
            $data['stockArticleList'] = array();


            $stockArticleList = $this->loadArticleList($data['stockId']);
            //var_dump($stockArticleList);
            if (is_array($stockArticleList) && count($stockArticleList) > 0){
                $data['stockArticleList'] = $stockArticleList;
            }
            //var_dump($_POST);
            if (isset($_POST['action'])) {
                switch (strtolower($_POST['action'])) {
                    case 'export':
                        //die("expot");
                        $this->exportCvs($stockArticleList);
                        $data['view'] = 'export';
                        break;
                    default:
                        echo "error, unknown action!!";
                }
            }

        }else{

            if (isset($_POST['action'])) {
                switch (strtolower($_POST['action'])) {

                    case 'abrechnen':
                        $data = $this->settle($data);
                        break;
                    default:
                        echo "error, unknown action!!";
                }

            }

            $data['view'] = 'index';

            $data['list']=$this->getStockList();


        }

        return $data;
    }

    protected function settle($data){

        try{
            $sth = $this->db->prepare("SELECT * FROM `stock` ORDER BY `from` ASC");
            //echo "3";
            $sth->execute();
            $res = $sth->fetchAll();


            $dTime = new DateTime();
            $createTime = $dTime->format(Database::$TimeFormat);
            $from = '';

            if (is_array($res) && count($res) > 0){
                $from = $res[count($res)-1]['settlement_time'];
                $where = 'id = '.$res[count($res)-1]['id'];
                $this->db->update('`stock`', array('settlement_time'=>$createTime, 'status'=>Database::$JA),$where);

            }


            $id = $this->db->insert('`stock`', array('from'=>$createTime,'status'=>Database::$Nein));

            if (!empty($from)){
                $data['msg'] = '<div class="successMsg">Der Lagerzustand ist von '.filter_var($from, FILTER_SANITIZE_STRING) .' bis '.filter_var($createTime, FILTER_SANITIZE_STRING) .' abgerechnet.</div>';
            }else {
                $data['msg'] = '<div class="successMsg">Der Lagerzustand ist abgerechnet.</div>';
            }

        }catch (Exception $e) {
            echo 'Exception: stock cannot be inserted: ',  $e->getMessage(), "\n";
        }

        return $data;
    }

    protected function getStockList(){
        $sth = $this->db->prepare("SELECT * FROM `stock` ORDER BY `from` DESC");
        //echo "3";
        $sth->execute();
        return  $sth->fetchAll();
    }

    protected function loadArticleList( $id ){

        $sql = "SELECT * FROM `article` LEFT JOIN `stock_article` ON article.id = stock_article.article_id WHERE stock_id = :id";

        $sth = $this->db->prepare($sql);

        //echo "3";
        $sth->execute(array(':id' => $id));
        return $sth->fetchAll();

    }

    protected function exportCvs($data, $tpl ='', $content =''){

        $content = '';
        $content .= implode( Database::$cvsDelimiter, array_keys( Database::$stockArticleSet ) );
        $content .= "\n";
        $list = $data;
        $fieldSet = array_values( Database::$stockArticleSet );

        foreach ( $list AS $item ) {
            $cnt = 1;
            foreach ( $fieldSet AS $field ) {
                $delimiter = Database::$cvsDelimiter;
                if ($cnt == count($fieldSet)){
                    $delimiter = "\n";
                }
                $content .=  $item[$field].$delimiter;
                $cnt++;
            }
        }

        Helper::download_send_headers('views/stock/export_tpl.php', $content, "lagerzustand");
    }
}